package com.beaven.model.data.user;

import com.beaven.model.Factory;
import com.beaven.model.data.DataSource;
import com.beaven.model.data.helper.UserHelper;
import com.beaven.model.model.api.RspModel;
import com.beaven.model.model.card.UserCard;
import com.beaven.model.model.db.User;
import java.util.List;
import rx.Subscriber;
import rx.subscriptions.CompositeSubscription;
import timber.log.Timber;

/**
 * author: Beaven
 * time: 2017/5/27 17:15
 */

public class ContactPresenter implements DataSource.SuccessCallBack<List<User>> {

  private ContactRepository contactRepository;
  private OnContractLoad load;
  private CompositeSubscription subscription;

  public ContactPresenter(OnContractLoad load) {
    contactRepository = new ContactRepository();
    this.load = load;
    subscription = new CompositeSubscription();
  }

  public void loadData() {
    contactRepository.load(this);
    Timber.e("网络请求--获取好友列表");
    subscription.add(UserHelper.getContacts().subscribe(new Subscriber<RspModel<List<UserCard>>>() {
      @Override public void onCompleted() {
        Timber.e("网络请求--获取好友列表---结束");
      }

      @Override public void onError(Throwable e) {
        Timber.e(e);
      }

      @Override public void onNext(RspModel<List<UserCard>> listRspModel) {
        if (listRspModel.isSuccess()) {
          List<UserCard> userCardList = listRspModel.getResult();
          if (userCardList == null || userCardList.size() == 0) return;
          Factory.getUserCenter().dispatchUser(userCardList.toArray(new UserCard[0]));
        } else {
          Factory.decodeRspCode(listRspModel, null);
        }
      }
    }));
  }

  public void loadLocal() {
    contactRepository.load(this);
  }

  public void destroy() {
    subscription.clear();
    contactRepository.dispose();
  }

  @Override public void notifyData() {
    load.notifyContract();
  }

  @Override public void loadDataSuccess(List<User> users) {
    Timber.i("接收数据库变更---好友列表");
    load.loadContract(users);
  }

  public interface OnContractLoad {
    void loadContract(List<User> users);

    void notifyContract();
  }
}
